package club.itstudio.itouc.controller.jw

import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.entity.JwSession
import club.itstudio.itouc.entity.OUCStudent
import club.itstudio.itouc.service.JwOps
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.lang.Exception
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletResponse

@RestController
class JwLogin(val jwOps: JwOps) {
    /**
     * 处理登录请求
     * @param userCode: 学号
     * @param password: 密码
     */
    @PostMapping("/jw/login")
    fun login(response: HttpServletResponse,
              @RequestParam userCode: String,
              @RequestParam password: String): Result<Any> {
        // 新建会话
        val session = JwSession(userCode, password)
        // 登录系统 验证账号密码
        jwOps.loginJw(session)
        // 保存会话
        session.save()
        // 添加cookie
        val cookie = Cookie("token", session.token)
        cookie.path = "/"
        response.addCookie(cookie)
        // 尝试获取学生信息
        try {
            OUCStudent.getByUserCode(userCode)
        }catch (e: Exception) {
            // 未保存信息则从教务系统获取
            jwOps.getStuGradeSpecialtyInfoFromJw(session).save()
        }
        return ResultUtil.success(data = session.token)
    }
}